<template>
	<view class="todo-list-task-detail task-detail-page">
		<view class="simple-card task-card m-x-1rem m-t-1rem" style="padding: 30rpx;">
			<view class="simple-header">
				<view class="simple-title">
					<view class="simple-status">
						<u-tag :text="taskStatusOptions[taskDetail.status]" color="#fff"
							:border-color="taskStatusColor[taskDetail.status]"
							:bg-color="taskStatusColor[taskDetail.status]">
						</u-tag>
					</view>
					<view class="simple-title-text">
						<span>{{ taskDetail.title }}</span>
					</view>
				</view>
			</view>
			<view class="simple-card-content" style="margin-top: 20rpx;">
				<view class="simple-card-content-row">
					<view class="simple-info">
						<view class="info-field">任务类型：</view>
						<view class="info-content">
							{{ taskTypeOptions[taskDetail.type] }}
						</view>
					</view>
				</view>
				<view class="simple-card-content-row">
					<view class="simple-info">
						<view class="info-field">指定完成日期：</view>
						<view class="info-content">
							{{ parseTime(taskDetail.finishDate) }}
						</view>
					</view>
				</view>
				<view class="simple-card-content-row">
					<view class="simple-info">
						<view class="info-field">任务内容：</view>
						<view class="info-richText" v-html="taskDetail.content"></view>
					</view>
				</view>
				<view class="simple-card-content-row">
					<view class="simple-info">
						<view class="info-field">执行人：</view>
						<view class="info-content">
							{{
		    taskDetail.taskPersonnels
		      ? taskDetail.taskPersonnels.userName
		      : ""
		  }}
						</view>
					</view>
				</view>
				<view class="simple-card-content-row">
					<view class="simple-info">
						<view class="info-field">参与者：</view>
						<view class="infoContent-box">
							<view class="info-content" v-for="(item, index) in taskDetail.taskPersonnel">
								<view v-if="item.type == 1">
									{{ item.userName }}
									<span v-if="index < taskDetail.taskPersonnel.length - 2">,</span>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-if="taskDetailAppendix && taskDetailAppendix.length > 0" class="simple-card-content-row">
					<view class="inner-appendix-list">
						<view class="appendix-list-title">附件列表：</view>
						<view v-for="appendixItem in taskDetailAppendix" :key="appendixItem.id" class="appendix-item">
							<span class="appendix-name">
								{{ appendixItem.filename }}
							</span>
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-tabs :list="list" :is-scroll="false" :current="current" @change="change"
			class="task-record-tabs m-x-1rem m-t-1rem" type="card" style="
        box-shadow: 0px 3px 14px 2px rgba(0, 0, 0, 0.05),
          0px 8px 10px 1px rgba(0, 0, 0, 0.06),
          0px 5px 5px -3px rgba(0, 0, 0, 0.1);
        border-radius: 10px;
      ">
		</u-tabs>

		<view class="task-record-tabs m-x-1rem m-t-1rem">
			<view style="width: 100%;" v-if="current == 0">
				<u-empty v-if="taskRecordData.length < 1" text="暂无记录" mode="list" style="margin-top: 100rpx;"></u-empty>
				<view v-for="taskRecord in taskRecordData" :key="taskRecord.id" class="trace-record">
					<p class="record-row">
						<span class="record-field">记录人：</span>
						<span class="record-content">{{ taskRecord["userName"] }}</span>
					</p>
					<p class="record-row">
						<span class="record-field">任务状态：</span>
						<span class="record-content">{{
				  taskStatusOptions[taskRecord.status]
				}}</span>
					</p>
					<p class="record-row">
						<span class="record-field">记录时间：</span>
						<span class="record-content">{{ taskRecord.createTime }}</span>
					</p>
					<p class="record-row">
						<span class="record-field">记录详情：</span>
						<span class="record-content">{{ taskRecord.content }}</span>
					</p>
					<view v-if="
				  taskRecord.taskRecordFileList &&
				  taskRecord.taskRecordFileList.length > 0
				" class="inner-appendix-list">
						<view class="appendix-list-title">附件列表：</view>
						<view v-for="appendixItem in taskRecord.taskRecordFileList" :key="appendixItem.id"
							class="appendix-item">
							<span class="appendix-name">
								<u-icon name="file-text"></u-icon>
								<span style="margin-left: 0.5rem">{{
				      appendixItem.filename
				    }}</span>
							</span>
						</view>
					</view>
				</view>
			</view>



			<view class="new-record" style="height: 900rpx;" v-if="current == 1">
				<u-form ref="newRecordFormRef" class="label-inner" :model="newRecordForm" :rules="newRecordFormRules"
					:borderBottom="false" labelPosition="top" label-width="100rpx">
					<u-form-item label="任务状态" prop="status">
						<u-input v-model="newRecordFormFont.status" type="text" :border="true" @click="show = true"
							:disabled="taskDetail.isables" />
						<u-select v-model="show" :list="taskStatusOptionsList" valueName="value"
							labelName="label"></u-select>
					</u-form-item>
					<u-form-item label="内容详情" prop="content" style="flex-direction: column">
						<u-input v-model="newRecordForm.content" :border="true" class="el-textarea" autosize
							type="textarea" />
					</u-form-item>
				</u-form>
				<view v-if="newRecordForm.taskRecordFileList.length > 0" class="form-item-appendix-list"
					style="margin-top: 20rpx;">
					<view v-for="appendixItem in newRecordForm.taskRecordFileList" :key="appendixItem.id"
						class="form-item-appendix-item">
						<view class="appendix-item-left">
							<u-icon name="file-text"></u-icon>
							<span style="margin-left: 0.5rem">{{appendixItem["filename"]}}</span>
						</view>
						<view class="appendix-item-right">
							<u-icon class="action-delete-appendix" name="clear"
								@click="removeRecordFile(appendixItem)" />
						</view>
					</view>
				</view>
				<view style="width: 100%;margin-top: 20rpx;">
					<view class="button-text" @click="onUpload">
						<u-icon name="file-text"></u-icon>
						<view>上传文件</view>
					</view>
					<!-- <u-upload :action="uploadConfig.url" :headers="uploadConfig.headers" :file-list="fileList" 
					:form-data="uploadConfig.data" @on-success="handleFileSuccess" :on-error="handleFileError"></u-upload> -->
				</view>
				<!-- <web-view src="https://v1.uviewui.com/"></web-view> -->
				<view style="width: 100%;margin-top: 20rpx;">
					<u-button type="primary" @click="newRecordFormSubmit()">
						提交
					</u-button>
				</view>
			</view>
		</view>

		<u-toast ref="uToast" />
		<l-file ref="lFile" @up-success="handleFileSuccess"></l-file>
	</view>
</template>
<script>
	import {
		taskStatusColor,
		taskStatusOptions,
		taskTypeOptions,
		taskStatusOptionsList
	} from "../../constants/taskConstant";
	// import { getTask } from "@/api/task";
	// import { addRecord, listRecord } from "@/api/record";
	// import { getToken } from "@/utils/auth";
	// import { parseTime } from "@/utils";
	// import { fileIconClass } from "@/utils/fileUtil";
	// import RouterUtilComposition from "@/composition/RouterUtilComposition";

	// ----- [ pre ] -----
	export default {
		data() {
			return {
				show: false,
				list: [{
					name: '追踪记录'
				}, {
					name: '新增记录'
				}],
				current: 0,
				taskId: "",
				recordTab: "跟踪记录",
				newRecordFormRef: null,
				newRecordForm: {
					taskId: "",
					status: "0",
					content: "",
					taskRecordFileList: [],
				},
				newRecordFormFont: {
					taskId: "",
					status: "进行中",
					content: "",
					taskRecordFileList: [],
				},
				taskStatusColor: [],
				taskStatusOptions: [],
				taskTypeOptions: [],
				isxt: null,
				taskDetail: {},
				taskDetailAppendix: {},
				taskStatusOptionsList: [],
				taskRecordData: [],
				uploadConfig: {
					// 是否禁用上传
					isUploading: false,
					// 设置上传的请求头部
					headers: {
						Authorization: uni.getStorageSync('token'),
					},
					data: {
						module: "cmdb.resource",
						["data" + "id"]: "resource",
						single: false,
						filetypes: "",
					},
					// 上传的地址
					url: "http://all.roywise.cn:8086/api" + "/system/attachment/attachment/upload",
				},
				newRecordFormRules: {
					// status: [{
					// 	required: true,
					// 	message: '请选择任务状态',
					// 	trigger: 'blur'
					// }],
					content: [{
						required: true,
						message: "请填写任务详情",
						trigger: "blur",
					}, ],
				},
			};
		},
		watch: {
			newRecordForm() {
				this.newRecordFormFont.status = taskStatusOptionsList[this.newRecordForm.status]
			}
		},
		onLoad: function(option) {
			console.log(option)
			this.taskStatusColor = taskStatusColor;
			this.taskStatusOptions = taskStatusOptions;
			this.taskTypeOptions = taskTypeOptions;
			this.taskStatusOptionsList = taskStatusOptionsList
			this.taskId = option.taskId
			this.newRecordForm.taskId = option.taskId
		},
		mounted() {
			this.getTask()
		},
		methods: {
			getTask() {
				this.$request('', '/serviceItems/wechat/task/' + this.taskId, 'get', {}, {}, ).then(res => {
					for (let i in res.data.taskPersonnel) {
						if (res.data.taskPersonnel[i].type == 0) {
							res.data.taskPersonnels = res.data.taskPersonnel[i];
							if (res.data.taskPersonnel[i].userId == res.data.loginUser.userId) {
								res.data.isables = false;
							} else {
								res.data.isables = true;
							}
						}
					}
					this.taskDetail = res.data;
					this.taskDetailAppendix = res.data["taskFileList"];
					this.getRecordList();
				})
			},
			getRecordList() {
				this.$request('', '/serviceItems/wechat/record/list', 'get', {
					taskId: this.taskId,
				}, {}, ).then(
					res => {
						this.taskRecordData = res.data;
					})
			},
			initRecordForm() {
				this.newRecordForm.content = "";
				this.newRecordForm.status = "";
				this.newRecordForm.taskRecordFileList.splice(0);
			},
			newRecordFormSubmit(formName) {
				this.$request('', '/serviceItems/wechat/record', 'post', this.newRecordForm, {}, ).then(
					res => {
						this.$refs.uToast.show({
							title: '提交成功',
							type: 'success'
						})
						this.initRecordForm();
						this.current = 0;
						this.getRecordList();
						// this.getRecordList();
					})
			},
			handleFileSuccess(response) {
				console.log(response)
				if (response.data.code === 200) {
					this.newRecordForm.taskRecordFileList.push({
						attachmentId: response.data.data.id,
						filename: response.data.data.name,
					});
				} else {
					this.$toast.fail("文件上传失败");
				}
			},
			handleFileError() {
				this.uploadConfig.isUploading = false;
				this.$toast.fail("文件上传失败");
			},

			removeRecordFile(target) {
				this.newRecordForm.taskRecordFileList =
					this.newRecordForm.taskRecordFileList.filter(
						(recordFile) => recordFile !== target
					);
			},
			/* 上传 */
			onUpload() {
				this.$refs.lFile.upload({
					//替换为你的上传接口地址
					url: "http://all.roywise.cn:8086/api" + "/system/attachment/attachment/upload",
					// 服务端接收附件的key
					name: 'file',
					//根据你接口需求自定义 (优先不传content-type,安卓端无法收到参数再传)
					header: {
						'Authorization': uni.getStorageSync('token'),
					},
					module: "cmdb.resource",
					["data" + "id"]: "resource",
					single: false,
					filetypes: "",
				});
			},
			downAppendix(appendixItem) {
				const tokenUrl = document.createElement("a");
				tokenUrl.href =
					process.env.VUE_APP_BASE_API +
					"/system/attachment/attachment/download/" +
					appendixItem.attachmentId;
				tokenUrl.target = "_self";
				tokenUrl.click();
			},
			parseTime(time, pattern) {
				if (arguments.length === 0 || !time) {
					return null;
				}
				const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
				let date;
				if (typeof time === "object") {
					date = time;
				} else {
					if (typeof time === "string" && /^[0-9]+$/.test(time)) {
						time = parseInt(time);
					} else if (typeof time === "string") {
						time = time
							.replace(new RegExp(/-/gm), "/")
							.replace("T", " ")
							.replace(new RegExp(/\.[\d]{3}/gm), "");
					}
					if (typeof time === "number" && time.toString().length === 10) {
						time = time * 1000;
					}
					date = new Date(time);
				}
				const formatObj = {
					y: date.getFullYear(),
					m: date.getMonth() + 1,
					d: date.getDate(),
					h: date.getHours(),
					i: date.getMinutes(),
					s: date.getSeconds(),
					a: date.getDay(),
				};
				const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
					let value = formatObj[key];
					// Note: getDay() returns 0 on Sunday
					if (key === "a") {
						return ["日", "一", "二", "三", "四", "五", "六"][value];
					}
					if (result.length > 0 && value < 10) {
						value = "0" + value;
					}
					return value || 0;
				});
				return time_str;
			},

			fileIconClass(fileName) {
				const fileNameArr = fileName.split(".");
				if (fileNameArr.length < 1) {
					return defaultName;
				}
				switch (fileNameArr[fileNameArr.length - 1].toLowerCase()) {
					case "jpg":
					case "jpeg":
					case "png":
					case "gif":
						return "icon-file-image";
					case "rar":
					case "7z":
					case "zip":
					case "gz":
					case "tar":
					case "iso":
					case "bz":
					case "bz2":
						return "icon-file-zip";
					case "pdf":
						return "icon-file-pdf";
					case "ppt":
						return "icon-file-ppt";
					case "doc":
					case "docx":
						return "icon-file-word";
					case "xls":
					case "xlsx":
						return "icon-file-excel";
					case "md":
						return "icon-file-markdown";
					default:
						return defaultName;
				}
			},
			change(index) {
				console.log(index)
				this.current = index;
			}
		},
	};
</script>
<style lang="scss">
	@import "../../styles/variables.scss";

	.button-text {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		border: #ccc dotted 1rpx;
		border-radius: 100rpx;
	}

	.todo-list-task-detail {
		overflow: scroll;
		background-color: #fff;
		height: 100vh;
	}

	.height-add {
		width: 100%;
		height: 200rpx;
	}

	.el-upload-dragger {
		width: 300rpx !important;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.el-upload {
		width: 100%;
	}

	.infoContent-box {
		display: flex;
		flex-flow: wrap;
		width: 100%;
	}

	.info-richText {
		width: 69%;

		img {
			width: 100%;
			height: auto;
		}
	}

	// .todo-list-task-detail {
	//   padding: 1rem;
	// }
</style>